package com.horsen.service.base.handler;

import com.horsen.common.util.R;
import com.horsen.common.util.ResultCodeEnum;
import com.horsen.service.base.exception.HseduException;
import com.horsen.service.base.util.ExceptionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.connection.PoolException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理器
 *
 * @author Horsen
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 自定义异常 用于封装RuntimeException
     *
     * @param e 异常
     * @return 统一返回结果实例
     */
    @ExceptionHandler(HseduException.class)
    @ResponseBody
    public R error(HseduException e) {
        log.error(ExceptionUtils.getMessage(e));
        return R.error(e.getCode(), e.getMessage());
    }

    /**
     * 默认错误
     *
     * @param e 异常
     * @return 统一返回结果实例
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e) {
        log.error(ExceptionUtils.getMessage(e));
        return R.error();
    }

    /**
     * SQL语法错误
     *
     * @param e 异常
     * @return 统一返回结果实例
     */
    @ExceptionHandler(BadSqlGrammarException.class)
    @ResponseBody
    public R badSqlGrammar(BadSqlGrammarException e) {
        log.error(ExceptionUtils.getMessage(e));
        return R.setResult(ResultCodeEnum.BAD_SQL_GRAMMAR);
    }

    /**
     * 主键重复错误
     *
     * @param e 异常
     * @return 统一返回结果实例
     */
    @ExceptionHandler(DuplicateKeyException.class)
    @ResponseBody
    public R duplicateKeyException(DuplicateKeyException e) {
        log.error(ExceptionUtils.getMessage(e));
        return R.setResult(ResultCodeEnum.DUPLICATE_KEY_EXCEPTION);
    }

    /**
     * Redis连接错误
     *
     * @param e 异常
     * @return 统一返回结果实例
     */
    @ExceptionHandler(PoolException.class)
    @ResponseBody
    public R redisConnectionPoolException(PoolException e) {
        log.error(ExceptionUtils.getMessage(e));
        return R.setResult(ResultCodeEnum.REDIS_CONNECTION_ERROR);
    }
}
